package controller;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter")
public class LoginFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
        resp.setContentType("text/html;charset=UTF-8");
        Cookie[] cookies = req.getCookies();
        String username = null;
        if (cookies == null) {
            resp.getWriter().write("<script language=javascript>alert('" + "您还未登录,请点击确定前往登录" + "');window.location='login.html'</script>");
        } else {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    username = String.valueOf(cookie);
                }
            }
        }
        if (req.getParameter("username") == null && username == null) {
            resp.getWriter().write("<script language=javascript>alert('" + "您还未登录,请点击确定前往登录" + "');window.location='login.html'</script>");
        } else {
            chain.doFilter(req, resp);
        }
    }
}
